package org.elanfox.intellicommunity.msg.dto;

import lombok.Data;
import org.elanfox.intellicommunity.common.ienum.base.CodeDescEnumHelper;
import org.elanfox.intellicommunity.common.utils.Jsr310Utils;
import org.elanfox.intellicommunity.msg.ienum.CmdEnums;
import org.elanfox.intellicommunity.msg.ienum.TagTypEnum;

import java.text.DecimalFormat;
import java.time.LocalDateTime;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/3/17
 */
@Data
public class RawTagDTO extends RawMsgDTO {
    private static final long serialVersionUID = -7193542473561258623L;

    /**
     * 类型
     */
    private TagTypEnum tagType;
    /**
     * 标签id
     */
    private long tagId;
    /**
     * 新触发器id
     */
    private long newTriggerId;
    /**
     * 旧触发器id
     */
    private long oldTriggerId;
    /**
     * 电量是否不足
     */
    private boolean batteryNotEnough;
    /**
     * 是否报警按钮
     */
    private boolean alarmedButton;
    /**
     * 拆除报警
     */
    private boolean dismantleAlarm;
    /**
     * 时间
     */
    private LocalDateTime time;

    public RawTagDTO(CmdEnums.Code cmdCode, String hexStr) {
        super(cmdCode, hexStr);
        String hexTagType = hexStr.substring(38, 40);
        this.tagType = CodeDescEnumHelper.getEnumTypeByCode(TagTypEnum.class, hexTagType);
        if (this.tagType == null) {
            this.tagType = TagTypEnum.OTHER;
        }
        this.tagId = Long.valueOf(hexStr.substring(40, 48), 16);
        this.newTriggerId = Long.valueOf(hexStr.substring(50, 54), 16);
        this.oldTriggerId = Long.valueOf(hexStr.substring(54, 58), 16);
        String binaryStatus = Integer.toBinaryString(Integer.parseInt(hexStr.substring(66, 68), 16));
        DecimalFormat df = new DecimalFormat("00000000");
        binaryStatus = df.format(Integer.valueOf(binaryStatus));
        this.batteryNotEnough = binaryStatus.charAt(0) == '1';
        this.alarmedButton = binaryStatus.charAt(1) == '1';
        this.dismantleAlarm = binaryStatus.charAt(2) == '1';
        long timestamp = Long.valueOf(hexStr.substring(70, 78), 16);
        this.time = Jsr310Utils.DateTime.of(timestamp * 1000);
    }

    @Override
    public String toString() {
        return "RawTagDTO{" +
                "tagType=" + tagType.getDesc() +
                ", tagId=" + tagId +
                ", newTriggerId=" + newTriggerId +
                ", oldTriggerId=" + oldTriggerId +
                ", batteryNotEnough=" + batteryNotEnough +
                ", alarmedButton=" + alarmedButton +
                ", dismantleAlarm=" + dismantleAlarm +
                ", time=" + time +
                ", cmdCode=" + getCmdCode().getDesc() +
                ", deviceAddr=" + getDeviceAddr() +
                '}';
    }
}
